import json

from rest_framework.response import Response
from rest_framework.views import APIView

from my.serializers import UserInfoSerializer


# Create your views here.
class UserInfoView(APIView):
    def get(self,request):
        user = request.user
        serializer = UserInfoSerializer(user)
        return Response({"code":0, "msg":"", "data":serializer.data})

    def put(self,request):
        # TODO:
        if request.data.get('id') != request.user.id:
            return Response({"code": 1, "msg": "无权修改其它用户的信息", "data": {
                "adjusted_id": request.data.get('id'),
                "user_id": request.user.id
            }})

        serializer = UserInfoSerializer(request.user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"code":0, "msg":"修改用户信息成功！", "data":None})
        return Response({"code": 1, "msg":str(serializer.errors), "data":None})

class UpdateView(APIView):
    def patch(self,request):
        avatar = request.data.get('avatar')
        serializer = UserInfoSerializer(request.user, data={'user_pic':avatar}, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"code": 0, "msg": "修改用户信息成功！", "data": serializer.data})
        return Response({"code": 1, "msg": serializer.errors, "data": None})


class UpdatePwdView(APIView):
    def patch(self,request):
        old_pwd = request.data.get('old_pwd')
        new_pwd = request.data.get('new_pwd')
        re_pwd = request.data.get('re_pwd')

        if new_pwd != re_pwd:
            return Response({"code": 1, "msg": "重复输入新密码不一致", "data": None})

        if not request.user.check_password(old_pwd):
            return Response({"code": 1, "msg": "原密码错误！", "data": None})

        request.user.set_password(new_pwd)
        request.user.save()  # 必须保存！
        return Response({"code": 0, "msg": "更新密码成功！", "data": None})


class MenusView(APIView):
    def get(self):

        return Response({"code":0, "message": "获取左侧菜单成功！", "data":None})